package com.sunday.aomicaichang.ui.main;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.adpter.IndexAdapter;
import com.sunday.aomicaichang.base.BaseApp;
import com.sunday.aomicaichang.constValues.ConstValue;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.ui.product.ProductClassifyActivity;
import com.sunday.aomicaichang.ui.widgets.PopAreaWindow;
import com.sunday.member.entity.CookBooks;
import com.sunday.member.entity.IndexData;
import com.sunday.member.entity.Village;
import com.sunday.member.entity.news.News;
import com.sunday.member.entity.product.Product;
import com.sunday.member.entity.product.ProductCategory;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class IndexFragment extends BaseFragment implements PopAreaWindow.OnOrderCreenPopConfirmListener {


    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.left_txt)
    TextView leftTxt;
    @Bind(R.id.right_menu)
    ImageView rightMenu;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;

    private IndexAdapter adapter;
    private LinearLayoutManager layoutManager;
    private long memberId;
    private Activity mActivity;
    int villageId;
    String villageName;

    public static IndexFragment newInstance() {
        IndexFragment fragment = new IndexFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_index, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        memberId = BaseApp.getInstance().getMember().getId();
        initParams();
        villageId = SharePerferenceUtils.getIns(mContext).getInt(ConstValue.AREA, 0);
        villageName=SharePerferenceUtils.getIns(mContext).getString(ConstValue.AREA_NAME,"选择小区");
        if (villageId == 0) {
            getVillages();
        } else {
            getData();
        }
        leftTxt.setText(villageName);
    }

    private void getVillages() {
        Call<ResultDO<List<Village>>> call = ApiClient.getApiAdapter().getVillage();
        call.enqueue(new Callback<ResultDO<List<Village>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Village>>> call, Response<ResultDO<List<Village>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    List<Village> villages = response.body().getResult();
                    if (!villages.isEmpty()) {
                        Village village = villages.get(0);
                        villageId = village.getId();
                        villageName=village.getName();
                        SharePerferenceUtils.getIns(mContext).putInt(ConstValue.AREA, villageId);
                        SharePerferenceUtils.getIns(mContext).putString(ConstValue.AREA_NAME, villageName);
                        leftTxt.setText(villageName);
                        getData();
                    }

                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Village>>> call, Throwable t) {
            }
        });
    }

    private void initView() {
        title.setText("奥密菜场");
        rightMenu.setVisibility(View.GONE);
        handlerRecyclerView();

    }

    private List<ProductCategory> categoryList = new ArrayList<>();
    private List<Product> productList = new ArrayList<>();
    private List<News> newsList = new ArrayList<>();
    private List<CookBooks> cookBooksList = new ArrayList<>();
    private List<News> imgList = new ArrayList<>();
    private List<Village> villageList = new ArrayList<>();

    private void handlerRecyclerView() {
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new IndexAdapter(mContext, imgList, newsList, cookBooksList, productList, categoryList);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getData1();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });
    }

    private void initParams() {
    }

    private void getData() {
        showLoadingDialog(0);
        String nonce = MD5Utils.random();//随机数
        String[] str1 = new String[]{"villageId", "nonce"};
        String[] str2 = new String[]{String.valueOf(villageId), nonce};
        Call<ResultDO<IndexData>> call = MemberClient.getApiAdapter().getIndexData(villageId, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<IndexData>>() {
            @Override
            public void onResponse(Call<ResultDO<IndexData>> call, Response<ResultDO<IndexData>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                ptrFrame.refreshComplete();
                ResultDO<IndexData> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    if (resultDO.getResult().getCategories() != null && !resultDO.getResult().getCategories().isEmpty()) {
                        categoryList.clear();
                        ProductCategory category1 = new ProductCategory();
                        category1.setName("每日签到");
                        category1.setImage("1");
                        /*ProductCategory category2=new ProductCategory();
                        category2.setName("菜谱库");
                        category2.setImage("2");*/
                        ProductCategory category3 = new ProductCategory();
                        category3.setName("积分商城");
                        category3.setImage("3");
                        categoryList.add(category1);
                        //categoryList.add(category2);
                        categoryList.add(category3);
                        categoryList.addAll(resultDO.getResult().getCategories());
                    }
                    if (resultDO.getResult().getProducts() != null && !resultDO.getResult().getProducts().isEmpty()) {
                        productList.clear();
                        productList.addAll(resultDO.getResult().getProducts());
                    }
                    if (resultDO.getResult().getCookbooks() != null && !resultDO.getResult().getCookbooks().isEmpty()) {
                        cookBooksList.clear();
                        cookBooksList.addAll(resultDO.getResult().getCookbooks());
                    }
                    if (resultDO.getResult().getImages() != null && !resultDO.getResult().getImages().isEmpty()) {
                        imgList.clear();
                        imgList.addAll(resultDO.getResult().getImages());
                    }

                    if (resultDO.getResult().getNews() != null && !resultDO.getResult().getNews().isEmpty()) {
                        newsList.clear();
                        newsList.addAll(resultDO.getResult().getNews());
                    }
                    adapter.notifyDataSetChanged();
                    updateView();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<IndexData>> call, Throwable t) {
                ptrFrame.refreshComplete();
            }
        });
    }

    private void getData1() {
        showLoadingDialog(0);
        int villageId = SharePerferenceUtils.getIns(mContext).getInt(ConstValue.AREA, 0);
        String nonce = MD5Utils.random();//随机数
        String[] str1 = new String[]{"villageId", "nonce"};
        String[] str2 = new String[]{String.valueOf(villageId), nonce};
        Call<ResultDO<IndexData>> call = MemberClient.getApiAdapter().getIndexData(villageId, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<IndexData>>() {
            @Override
            public void onResponse(Call<ResultDO<IndexData>> call, Response<ResultDO<IndexData>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                ptrFrame.refreshComplete();
                ResultDO<IndexData> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    if (resultDO.getResult().getCategories() != null && !resultDO.getResult().getCategories().isEmpty()) {
                        categoryList.clear();
                        ProductCategory category1 = new ProductCategory();
                        category1.setName("每日签到");
                        category1.setImage("1");
                        /*ProductCategory category2=new ProductCategory();
                        category2.setName("菜谱库");
                        category2.setImage("2");*/
                        ProductCategory category3 = new ProductCategory();
                        category3.setName("积分商城");
                        category3.setImage("3");
                        categoryList.add(category1);
                        //categoryList.add(category2);
                        categoryList.add(category3);
                        categoryList.addAll(resultDO.getResult().getCategories());
                    }
                    if (resultDO.getResult().getProducts() != null && !resultDO.getResult().getProducts().isEmpty()) {
                        productList.clear();
                        productList.addAll(resultDO.getResult().getProducts());
                    }
                    if (resultDO.getResult().getCookbooks() != null && !resultDO.getResult().getCookbooks().isEmpty()) {
                        cookBooksList.clear();
                        cookBooksList.addAll(resultDO.getResult().getCookbooks());
                    }
                    if (resultDO.getResult().getImages() != null && !resultDO.getResult().getImages().isEmpty()) {
                        imgList.clear();
                        imgList.addAll(resultDO.getResult().getImages());
                    }

                    if (resultDO.getResult().getNews() != null && !resultDO.getResult().getNews().isEmpty()) {
                        newsList.clear();
                        newsList.addAll(resultDO.getResult().getImages());
                    }
                    adapter.notifyDataSetChanged();

                    updateView();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<IndexData>> call, Throwable t) {
                ptrFrame.refreshComplete();
            }
        });
    }

    @OnClick({R.id.right_menu, R.id.left_txt})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_menu:
                intent = new Intent(mContext, ProductClassifyActivity.class);
                startActivity(intent);
                break;
            case R.id.left_txt:
//                PopAreaWindow popWindow = new PopAreaWindow(getActivity(),mContext,this);
//                popWindow.showPopupWindow(leftTxt);
//                intent=new Intent(mContext,SelectAreaActivity.class);
//                startActivity(intent);
                showDialogs();
                break;
        }
    }

    private void showDialogs() {
        final AlertDialog myDialog = new AlertDialog.Builder(mContext).create();
        myDialog.setView(((Activity) mContext).getLayoutInflater().inflate(R.layout.pop_area, null));
        myDialog.show();
        myDialog.getWindow().setContentView(R.layout.pop_area);
        final LinearLayout lyArea = (LinearLayout) myDialog.findViewById(R.id.ly_area);
        Call<ResultDO<List<Village>>> call = ApiClient.getApiAdapter().getVillage();
        call.enqueue(new Callback<ResultDO<List<Village>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Village>>> call, Response<ResultDO<List<Village>>> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    final List<Village> villages = response.body().getResult();
                    lyArea.removeAllViews();
                    if (villages.size() != 0) {
                        for (final Village v2 : villages) {
                            View v1 = LayoutInflater.from(mContext).inflate(R.layout.item_area, null);
                            TextView area = (TextView) v1.findViewById(R.id.tv_area);
                            if (!TextUtils.isEmpty(v2.getName()))
                                area.setText(v2.getName());
                            area.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    SharePerferenceUtils.getIns(mContext).putInt(ConstValue.AREA, v2.getId());
                                    SharePerferenceUtils.getIns(mContext).putString(ConstValue.AREA_NAME, v2.getName());
                                    if (v2.getName() != null)
                                        leftTxt.setText(v2.getName());
                                    myDialog.dismiss();
                                    getData1();
                                }
                            });
                            lyArea.addView(v1);
                        }
                    }

                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Village>>> call, Throwable t) {
            }
        });
    }

    private void updateView() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @Override
    public void confirmClick(int result) {

    }
}
